package hu.myai.controller;

import hu.myai.model.db.AxHistory;
import hu.myai.util.DatabaseUtil;
import hu.myai.util.DownloadUtil;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityTransaction;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;

public class SaveHistoryASX {

	private static final ILogger log = LoggerFactory.getLogger(SaveHistoryASX.class);

	// for database util reference
	private DatabaseUtil dbUtil = new DatabaseUtil();

	DownloadUtil downloadUtil = new DownloadUtil();

	public SaveHistoryASX() {
	}

	public boolean saveTodayHistory() {
		return saveTodayHistory(downloadUtil.getASXCompanyList());
	}

	public boolean saveTodayHistory(List<String> symbolList) {

		EntityTransaction tx = dbUtil.entityManager.getTransaction();
		tx.begin();

		try {
			int i = 1;
			for (String symbol : symbolList) {

				/** check if it is a ordinary stock or not */
				if (symbol.length() == 3) {

					saveCandle(symbol);

					if (i % 20 == 0) {
						tx.commit();
						log.info("Commit...");
						tx.begin();
					}
					i++;
				}
			}
		} catch (Exception ex) {
			// Use Log4j
			log.error("Exception thrown while initializing the ASX. Message is : " + ex.getMessage()); // LOG4J
			ex.printStackTrace();
			tx.rollback();
			return false;
		}

		tx.commit();
		dbUtil.entityManager.clear();

		return true;

	} // End method initInputStream

	public boolean saveCandle(String symbol) {

		Date date = new Date();
		try {
			// get saved record

			AxHistory webHistory = downloadUtil.getCandle(symbol);

			// check the history is already saved or not.
			//TODO does not care about non traiding days
			Integer savedRecord = dbUtil.getSavedHistoryID(date, symbol); 
			if(savedRecord != null)
				webHistory.setId(savedRecord);
			
			// get and set the parent of this record
			AxHistory lastRecord = dbUtil.getLastHistory(date, symbol);
			webHistory.setParent(lastRecord);

			dbUtil.entityManager.merge(webHistory);
			log.debug("It is done: " + symbol);

		} catch (Exception ex) {
			// Use Log4j
			log.error("Exception thrown while initializing the ASX. Message is : " + ex.getMessage()); // LOG4J
			return false;
		}

		return true;
	}
}
